package com.tianruan.dc.modules.sys.user.api;

import com.tianruan.dc.common.utils.response.VResponse;
import com.tianruan.dc.modules.sys.user.entity.dto.SmsCodeDTO;
import com.tianruan.dc.modules.sys.user.entity.dto.UserDTO;
import com.tianruan.dc.modules.sys.user.service.ISmsCodeService;
import com.tianruan.dc.modules.sys.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import static com.tianruan.dc.common.constant.GlobalExceptionEnum.*;


@RestController
public class SmsCodeController {

    @Autowired
    private ISmsCodeService iSmsCodeService;


    /**
     * 发送短信验证码
     * @param smsCodeDTO
     * @return
     */
    @PostMapping("/static/sendSmsCode")
    public VResponse<Object> sendSmsCode(@RequestBody SmsCodeDTO smsCodeDTO) {
        try {
            //发送验证码
            if(smsCodeDTO.getPhone()!=null&&smsCodeDTO.getPhone().matches("^((13[0-9])|(14[579])|(15([0-3,5-9]))|(16[6])|(17[0-3,5-8])|(18[0-9]|19[89]))\\d{8}$")){
                iSmsCodeService.sendSmsCode(smsCodeDTO.getPhone());
                return VResponse.result(SUCCESS_TO_SENDSMSCODE);
            }else{
                return VResponse.result(FAIL_TO_SENDSMSCODE);
            }
        } catch (Exception e) {
            return VResponse.result(FAIL_TO_SENDSMSCODE);
        }
    }

    /**
     * 小程序端绑定手机
     * @param id
     * @param code
     * @param phone
     * @return
     */

    @PostMapping("/api/bind")
    public VResponse<Object> bind(@RequestParam("id") String id,@RequestParam("code") String code, @RequestParam("phone") String phone) {
        try {
            if(iSmsCodeService.checkId(id)){
                if (iSmsCodeService.check(phone, code)) {
                    iSmsCodeService.bindphone(id, phone);
                    return VResponse.result(SUCCESS_TO_BIND);
                }else{
                    return VResponse.result(ERROP_CODE);
                }
            }else{
                return VResponse.result(FAIL_TO_BIND);
            }
        } catch (Exception e) {
            return VResponse.result(FAIL_TO_BIND);
        }
    }
}
